<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Db;
use think\facade\Cache;
class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('authorization');
        if ($token) {
            $method = 'Bearer';
            //去除token中可能存在的bearer标识
            $token = trim(str_ireplace($method, '', $token));
            // die($token);
            $user = Cache::get($token);
            if (!$user) {
                return fail(null,'未登录');
            }
            $request->user = $user;
            return $next($request);
        }else{
            return $next($request);
        }
    }
    public function handle1($request, \Closure $next)
    {
        $token = $request->header('authorization');
        $user = Db::table('users')->where('token', $token)->value('token');
        if (!empty($user)) {
            return $next('success');
        } else {
            return fail(null,'token失效');
        }
    }
}
